package com.lin.missyou.api.v1;

import com.github.wxpay.sdk.LinWXPayConfig;
import com.lin.missyou.core.interceptors.ScopeLevel;
import com.lin.missyou.exception.http.ParameterException;
import com.lin.missyou.lib.LinWxNotify;
import com.lin.missyou.service.WxPaymentNotifyService;
import com.lin.missyou.service.WxPaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Positive;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

@RequestMapping("payment")
@RestController
@Validated
public class PaymentController {

    @Autowired
    private WxPaymentService wxPaymentService;

    @Autowired
    private WxPaymentNotifyService wxPaymentNotifyService;

    @PostMapping("/pay/order/{id}")
    @ScopeLevel
    public Map<String, String> preWxOrder(@PathVariable @Positive Long id) {
        Map<String, String> miniPayParams = this.wxPaymentService.preOrder(id);
        return miniPayParams;
    }

    @RequestMapping("/wx/notify")
    public String payCallback(HttpServletRequest request) {
        InputStream s = null;
        try {
            s = request.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            return LinWxNotify.fail();
        }
        String xml = LinWxNotify.readNotify(s);
        try {
            this.wxPaymentNotifyService.processPayNotify(xml);
        } catch (Exception e) {
            e.printStackTrace();
            return LinWxNotify.fail();
        }
        return LinWxNotify.success();
    }

    /**
     * 跳过微信支付的流程
     * @param map
     * @return
     */
    @RequestMapping("/wx/notify/copy")
    public String payCallback1(@RequestBody Map<String, String> map) {
        if (map == null) {
            throw new ParameterException(9999);
        }
        try {
            this.wxPaymentNotifyService.processPayNotifyCopy(map);
        } catch (Exception e) {
            e.printStackTrace();
            return LinWxNotify.fail();
        }
        return LinWxNotify.success();
    }
}
